package houduan;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "RegisterServlet", urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/lczmysql";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("newUsername");
        String password = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        if (username == null || username.isEmpty() || password == null || password.isEmpty() || confirmPassword == null || confirmPassword.isEmpty()) {
            sendErrorResponse(response, "注册信息不能为空", HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (!password.equals(confirmPassword)) {
            sendErrorResponse(response, "密码不一致", HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        try (Connection connection = getConnection()) {
            if (isUsernameExists(connection, username)) {
                sendErrorResponse(response, "用户名已存在", HttpServletResponse.SC_CONFLICT);
                return;
            }

            String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, username);
                statement.setString(2, password);

                int rowsAffected = statement.executeUpdate();
                if (rowsAffected > 0) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                    try (PrintWriter writer = response.getWriter()) {
                        writer.write("注册成功，请登录！");
                    }
                } else {
                    sendErrorResponse(response, "注册失败，请稍后重试", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            }

        } catch (SQLException | ClassNotFoundException e) {
            handleException(response, e);
        }
    }

    private Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    private boolean isUsernameExists(Connection connection, String username) throws SQLException {
        String sql = "SELECT COUNT(*) FROM users WHERE username = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, username);
            try (ResultSet resultSet = statement.executeQuery()) {
                return resultSet.next() && resultSet.getInt(1) > 0;
            }
        }
    }

    private void sendErrorResponse(HttpServletResponse response, String message, int statusCode) throws IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(statusCode);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(message);
        }
    }

    private void handleException(HttpServletResponse response, Exception e) throws IOException {
        sendErrorResponse(response, "服务器内部错误，请稍后再试", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        e.printStackTrace();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 可以调用 doPost 方法或者重定向到登录页面
        this.doPost(request, response);
    }
}
